﻿using System;
using System.Linq;
using Enyim.Caching;
using Ayatta.Contract;
using Web.Base.Extensions;
using Web.My.Models;
using System.Web.Mvc;
using Web.Base.Security;
using Web.Base.Components;
using Ayatta.Contract.Domain;
using Ayatta.Contract.Component;

namespace Web.My.Controllers
{
    public class OrderController : MyBaseController
    {
        public OrderController(ILogService logService, IBaseService baseService, IExtraService extraService,
                               IStoreService storeService, IOrderService orderService, IGameService gameService,
                               IAuctionService auctionService, IPassportService passportService,
                               IPaymentService paymentService, IMemcachedClient memcachedClient)
            : base(logService, baseService, extraService, storeService, orderService, gameService, auctionService, passportService, paymentService, memcachedClient)
        {
        }

        /// <summary>
        /// 订单列表
        /// </summary>
        /// <param name="page">当前页</param>
        /// <param name="size">分页大小</param>
        /// <param name="id">订单号</param>
        /// <param name="nick">商家昵称</param>
        /// <param name="title">商品标题</param>
        /// <param name="category">订单类型</param>
        /// <param name="orderStatus">订单状态</param>
        /// <param name="commentStatus">评论状态</param>
        /// <param name="beginDate">开始时间</param>
        /// <param name="endDate">结束时间</param>
        /// <returns></returns>
        public ActionResult Index(int page = 1, int size = 20, string id = null, string nick = null, string title = null,
            OrderCategory category = OrderCategory.Normal, OrderStatus? orderStatus = null, byte? commentStatus = null, DateTime? beginDate = null, DateTime? endDate = null)
        {
            var identity = User.Identity.Identity();
            var model = new OrderControllerModel.Index();
            model.Id = id;
            model.Nick = nick;
            model.Title = title;
            model.Category = category;
            model.Status = orderStatus;
            model.CommentStatus = commentStatus;
            model.BeginDate = beginDate;
            model.EndDate = endDate;
            var orders = OrderService.GetPagedOrders(page, size, id, identity.Id, nick, false, title, category, orderStatus, commentStatus, beginDate, endDate).ToPagedList(page, size);
            if (orders.Count > 0 && category != OrderCategory.IntegralExchange)
            {
                var orderIds = orders.Select(o => o.Id).ToArray();
                var orderItems = OrderService.GetOrderItems(orderIds);
                foreach (var order in orders)
                {
                    order.OrderItems = orderItems.Where(o => o.OrderId == order.Id).ToList();
                }
            }
            model.Orders = orders;
            return View(model);
        }

        //public ActionResult Auction(int page = 1, int size = 20)
        //{
        //    var identity = User.Identity.Identity();
        //    var model = new OrderControllerModel.Auction();
        //    model.Orders = AuctionService.GetPagedAuctionOrder(page, size, identity.Id).ToPagedList(page, size);
        //    return View(model);
        //}

        /// <summary>
        /// 订单详细信息
        /// </summary>
        /// <param name="param">订单号</param>
        /// <returns></returns>
        public ActionResult Detail(string param)
        {
            var identity = User.Identity.Identity();
            var model = new OrderControllerModel.Detail();
            var order = OrderService.GetOrder(param, identity.Id, true);
            model.Order = order;
            if (order.Status == OrderStatus.SellerSendPart || order.Status == OrderStatus.WaitBuyerConfirm || order.Status == OrderStatus.Finished)
            {
                model.Shippings = OrderService.GetOrderShippings(param);
            }
            return View(model);
        }

        /// <summary>
        /// 订单备忘
        /// </summary>
        /// <param name="param">订单号</param>
        /// <returns></returns>
        public ActionResult Memo(string param)
        {
            var identity = User.Identity.Identity();
            var model = OrderService.GetOrderMemo(param, identity.Id, false);
            return PartialView(model);
        }

        /// <summary>
        /// 订单备忘
        /// </summary>
        /// <param name="param">订单号</param>
        /// <param name="flag">Flag</param>
        /// <param name="memo">备忘</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Memo(string param, byte? flag, string memo)
        {
            var result = new SkResult<string>();
            if (memo.Length > 100)
            {
                result.Message = "备忘不能超过100个字！";
                return Json(result);
            }
            if (Request.IsAuthenticated)
            {
                var identity = User.Identity.Identity();
                var status = OrderService.UpdateOrderMemo(param, identity.Id, false, flag, memo);
                if (status)
                {
                    result.Status = true;
                }
                else
                {
                    result.Message = "备忘失败！";
                }
            }
            else
            {
                result.Message = "请登录！";
            }
            return Json(result);
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="param">订单号</param>
        /// <returns></returns>
        public ActionResult Cancel(string param)
        {
            var identity = User.Identity.Identity();
            var model = new SkResult<Order>();
            if (Request.IsAuthenticated)
            {
                var order = OrderService.GetOrderStatus(param, identity.Id, false);
                if (order == null)
                {
                    model.Message = "订单不存在！";
                }
                else
                {
                    if (order.Status == OrderStatus.Pending || order.Status == OrderStatus.WaitBuyerPay)
                    {
                        model.Status = true;
                        model.Data = order;
                    }
                    else
                    {
                        model.Message = "该订单当前状态不可关闭交易！";
                    }
                }
            }
            else
            {
                model.Message = "登录超时请重新登录！";
            }
            return PartialView(model);
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="param">订单号</param>
        /// <param name="reason">取消原因</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Cancel(string param, string reason)
        {
            var result = new SkResult<Order>();
            var identity = User.Identity.Identity();
            var order = OrderService.GetOrderStatus(param, identity.Id, false);
            if (order == null)
            {
                result.Message = "订单不存在！";
                return Json(result);
            }
            if (order.Status == OrderStatus.Pending || order.Status == OrderStatus.WaitBuyerPay)
            {
                var status = OrderService.UpdateOrderStatus(param, identity.Id, false, OrderStatus.Canceled, order.Version, reason);
                if (status)
                {
                    result.Status = true;
                }
                else
                {
                    result.Message = "取消订单失败！";
                }
            }
            else
            {
                result.Message = "该订单当前状态不可取消！";
            }
            return Json(result);
        }

        /// <summary>
        /// 修改补充留言
        /// </summary>
        /// <param name="param">订单号</param>
        /// <returns></returns>
        public ActionResult Message(string param)
        {
            var identity = User.Identity.Identity();
            var model = OrderService.GetOrderMemo(param, identity.Id, false);
            return PartialView(model);
        }

        /// <summary>
        /// 修改补充留言
        /// </summary>
        /// <param name="param">订单号</param>
        /// <param name="message">留言信息</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Message(string param, string message)
        {
            var result = new SkResult<string>();
            if (message.Length > 200)
            {
                result.Message = "留言信息不能超过200个字！";
                return Json(result);
            }
            if (Request.IsAuthenticated)
            {
                var identity = User.Identity.Identity();
                var status = OrderService.UpdateOrderBuyerMessage(param, identity.Id, message);
                if (status)
                {
                    result.Status = true;
                }
                else
                {
                    result.Message = "更新留言信息失败！";
                }
            }
            else
            {
                result.Message = "超时，请重新登录！";
            }
            return Json(result);
        }

        /// <summary>
        /// 编辑订单
        /// </summary>
        /// <param name="param">订单号</param>
        /// <returns></returns>
        public ActionResult Edit(string param)
        {
            var identity = User.Identity.Identity();
            var model = new OrderControllerModel.Detail();
            model.Order = OrderService.GetOrder(param, identity.Id, true);
            return View(model);
        }

        /// <summary>
        /// 确认收货
        /// </summary>
        /// <param name="param">物流订单号</param>
        /// <returns></returns>
        public ActionResult Confirm(string param)
        {
            var result = new SkResult<Order>();
            var identity = User.Identity.Identity();
            var shipping = OrderService.GetShipping(param);
            if (!shipping.IsOnline && shipping.Status == ShippingStatus.Created)
            {
                result.Status = OrderService.ConfirmOrder(param, identity.Id);
            }

            ViewBag.Sidebar = false;
            return View(result);
        }

        /// <summary>
        /// 订单支付 检查订单状态等
        /// </summary>
        /// <param name="param">订单号</param>
        /// <returns></returns>
        public ActionResult Pay(string param)
        {
            var url = string.Empty;
            var identity = User.Identity.Identity();

            var order = OrderService.GetOrder(param, identity.Id);
            if (order != null)
            {
                var trade = PaymentService.GetUserTrade(param, identity.Id);
                if (trade != null)
                {
                    if (trade.Status != UserTradeStatus.Pending && order.Status != OrderStatus.WaitBuyerPay)
                    {
                        url = "/order/detail/" + param;
                    }
                    else
                    {
                        url = WebSite.Pay + "/order?param=" + param;
                    }
                }
                else
                {
                    if (order.Category == OrderCategory.Auction)
                    {
                        url = "/order/auction/" + param;
                    }
                    else
                    {
                        var status = PaymentService.CreateUserTrade(order.ToTrade());
                        if (status)
                        {
                            OrderService.UpdateOrderStatus(param, identity.Id, false, OrderStatus.WaitBuyerPay, order.Version);
                        }
                        url = WebSite.Pay + "/order?param=" + param;
                    }
                }
            }
            return Redirect(url);
        }

        /// <summary>
        /// 竞购订单处理
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public ActionResult Auction(string param)
        {
            ViewBag.Sidebar = false;

            var identity = User.Identity.Identity();

            var order = OrderService.GetOrder(param, identity.Id);
            if (order != null)
            {
                var trade = PaymentService.GetUserTrade(param, identity.Id);
                if (trade != null)
                {
                    string url;
                    if (trade.Status != UserTradeStatus.Pending && order.Status != OrderStatus.Pending)
                    {
                        url = "/order/detail/" + param;
                    }
                    else
                    {
                        url = WebSite.Pay + "/order/?param=" + param;
                    }
                    return Redirect(url);
                }
                var model = new OrderControllerModel.Auction();
                //var locations = MemcachedClient.Put(CacheKey.Extra.Locations, BaseService.GetLocations);

                var addresses = GetUserAddresses(identity.Id).Where(o => o.Category == AddressCategory.Receive).ToList();
                var address = addresses.OrderByDescending(o => o.IsDefault).FirstOrDefault();
                var invoices = PassportService.GetUserInvoices(identity.Id);
                var invoice = invoices.OrderByDescending(o => o.IsDefault).FirstOrDefault();
                model.UserAddresses = addresses;
                model.UserAddress = address;
                model.UserInvoices = invoices;
                model.UserInvoice = invoice;
                model.Order = order;

                //model.Areas = address;
                return View(model);
            }
            return Redirect("/order");
        }

        [HttpPost]
        public ActionResult Auction(string param, UserAddress userAddress, UserInvoice userInvoice)
        {
            var identity = User.Identity.Identity();
            var order = OrderService.GetOrder(param, identity.Id);
            if (order.Status == OrderStatus.WaitBuyerPay)
            {
                var url = WebSite.Pay + "/order/?param=" + param;
                Redirect(url);
            }
            var areas = GetAreaNames(userAddress.AreaId, GetAreas());
            userAddress.Province = areas.Item1;
            userAddress.City = areas.Item2;
            userAddress.District = areas.Item3;
            var status = OrderService.SetOrderAddressInvoice(order.Id, identity.Id, userAddress, userInvoice);
            if (status)
            {
                //var title = "竞购：" + auctionOrder.Name;
                status = PaymentService.CreateUserTrade(order.ToTrade());
                if (status)
                {
                    OrderService.UpdateOrderStatus(param, identity.Id, false, OrderStatus.WaitBuyerPay, order.Version);

                    var url = WebSite.Pay + "/order/?param=" + param;
                    Redirect(url);
                }
            }
            return Redirect("/order/auction/" + param);
        }

        /// <summary>
        /// 竞拍获得的拍品兑换为积分或免费拍币
        /// </summary>
        /// <param name="param">订单Id</param>
        /// <returns></returns>
        public ActionResult Exchange(string param)
        {
            var identity = User.Identity.Identity();
            var exchange = OrderService.GetOrderExchangeDetail(param, identity.Id);
            if(exchange!=null)
            {
                var order = OrderService.GetOrder(param, identity.Id);
                if (order.Category == OrderCategory.Auction && order.DiffBuy)
                {

                }
            }
            
            return PartialView();
        }

        /// <summary>
        /// 竞拍获得的拍品兑换为积分或免费拍币
        /// </summary>
        /// <param name="param">订单Id</param>
        /// <param name="exchange">兑换目标</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ConfirmExchange(string param,OrderExchange exchange)
        {
            var identity = User.Identity.Identity();
            var result = new SkResult<string>();
            var detail = OrderService.GetOrderExchangeDetail(param, identity.Id);
            if (detail != null)
            {
                var time = detail.CreatedOn.ToString("yyyy-MM-dd HH:mm");
                var text = detail.Category == 0 ? "积分" : detail.Category == 1 ? "免费拍币" : string.Empty;
                result.Message = string.Format("您已于{0}选择将该订单兑换为{1}！", time, detail.Amount + text);
            }
            else
            {
                var order = OrderService.GetOrder(param, identity.Id);
                if (order.Category != OrderCategory.Auction || (order.Category == OrderCategory.Auction && order.DiffBuy))
                {
                    result.Message = "该订单不支持兑换！";
                    return Json(result);
                }
                
            }
            
            return Json(result);
        }

        public ActionResult Test()
        {
            var model = OrderService.Test();
            return Json(model, JsonRequestBehavior.AllowGet);
        }
    }
}
